Telegram Group & Telegram Channel
🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/javaproglib/6561
Create:
Last Update:

🎯 Как быстро настроить кеширование в Spring Boot

Писать кеш руками через HashMap или страдать с вручную настроенными TTL — скучно, долго и ненадёжно. В Spring Boot всё уже готово: включаем, настраиваем, и поехали!

1️⃣ Добавляем зависимость

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>

ИЛИ

implementation 'org.springframework.boot:spring-boot-starter-cache'


2️⃣ Включаем кеширование

Добавляем простую аннотацию над главным классом приложения (или конфиг классом):
@SpringBootApplication
@EnableCaching
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}


3️⃣ Кешируем методы сервисов

Используем аннотацию @Cacheable на тех методах, которые часто выполняются и редко меняются:
@Service
public class UserService {

@Cacheable(value = "users", key = "#id")
public User getUserById(Long id) {
simulateSlowService();
return userRepository.findById(id).orElseThrow();
}

private void simulateSlowService() {
Thread.sleep(3000);
}
}


Теперь при повторном вызове метода с тем же параметром ответ прилетит мгновенно.

4️⃣ Настройка TTL и конфигурация кеша

В Spring Boot по умолчанию используется простой ConcurrentMap (без TTL). Если хочешь TTL и прочие плюшки, подключайте Caffeine:

spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=500,expireAfterAccess=10m


Кеш будет жить максимум 10 минут и не разрастаться до бесконечности.

5️⃣ Очистка кеша

Если нужно принудительно почистить кеш после обновления данных, используем @CacheEvict:
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, User updatedUser) {
userRepository.save(updatedUser);
}


💬 Хранили когда-нибудь кеш в мапе?

🐸 Библиотека джависта #буст

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tg-me.com/javaproglib/6561

View MORE
Open in Telegram


Библиотека джависта | Java Spring Maven Hibernate Telegram | DID YOU KNOW?

Date: |

The seemingly negative pandemic effects and resource/product shortages are encouraging and allowing organizations to innovate and change.The news of cash-rich organizations getting ready for the post-Covid growth economy is a sign of more than capital spending plans. Cash provides a cushion for risk-taking and a tool for growth.

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Библиотека джависта | Java Spring Maven Hibernate from cn


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM USA